<template>
  <view class="bg-white order-details">
    <nav-bar color="white" bg-color="black" title="退菜" show-back></nav-bar>
    <u-row gutter="50rpx" customStyle="padding:20rpx 30rpx;align-items:flex-start;">
      <u-col span="6">
        <text class="text-lg font-bold block my-5rpx">菜品列表</text>
        <text class="text-sm block my-5rpx text-slate-400">显示的单价为折扣后的价格</text>
        <view class="my-10rpx">
          <text class="text-base font-bold mr-10rpx"> 订单号：{{ details.buffetOrderId }}</text>
          <text class="text-base font-bold"> 实付金额: ￥ {{ formatMoney(details.amountcollected) || "-" }} </text>
        </view>
        <uni-table :loading="pageStatus.loading" class="food-list" stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" class="fixed-left">序号</uni-th>
            <uni-th align="center">菜品名称</uni-th>
            <uni-th align="left">单价（元）</uni-th>
            <uni-th align="left">数量</uni-th>
            <uni-th align="left">合计（元）</uni-th>
            <uni-th align="left">操作</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in orderList" :key="item.buffetOrderItemId">
            <uni-td align="center" class="fixed-left">{{ index + 1 }}</uni-td>
            <uni-td align="center">{{ item.foodName }}</uni-td>
            <uni-td align="center">{{ item.memberPrice || item.price || "-" }}</uni-td>
            <uni-td align="center">{{ item.foodNum }}</uni-td>
            <uni-td align="center">{{ item.foodNum * (item.memberPrice || item.price) }}</uni-td>
            <uni-td align="center">
              <view>
                <u-button
                  disabled
                  color="grey"
                  size="small"
                  v-if="item.refundQuantity && item.refundQuantity == item.foodNum"
                  @click="clickReturnDishes(item)"
                >
                  已退</u-button
                >
                <u-button
                  type="primary"
                  size="small"
                  v-else-if="!haveRetuenDishes(item)"
                  @click="clickReturnDishes(item)"
                  >退菜</u-button
                >
                <u-button size="small" disabled color="grey" v-else>退菜中</u-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="p-10rpx text-base bg-slate-100">
          <text class="mr-20rpx"
            >菜品数量：
            <text class="font-bold">
              {{ orderList.length }}
            </text>
          </text>
          <text
            >金额：
            <text class="font-bold"> ￥{{ formatMoney(totalMoney) }} </text>
          </text>
        </view>
      </u-col>
      <u-col span="6">
        <text class="text-lg font-bold block my-5rpx">已选退菜列表</text>
        <view class="my-10rpx">
          <text class="text-base font-bold mr-10rpx"> </text>
          <text class="text-base font-bold"> </text>
        </view>
        <uni-table :loading="pageStatus.loading" class="food-list" stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" class="fixed-left">序号</uni-th>
            <uni-th align="center">菜品名称</uni-th>
            <uni-th align="left">单价（元）</uni-th>
            <uni-th align="left">数量</uni-th>
            <uni-th align="left">合计（元）</uni-th>
            <uni-th align="left">操作</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in retuenDishesList" :key="item.buffetOrderItemId">
            <uni-td align="center" class="fixed-left">{{ index + 1 }}</uni-td>
            <uni-td align="center">{{ item.foodName }}</uni-td>
            <uni-td align="center">{{ item.memberPrice || item.price || "-" }}</uni-td>
            <uni-td align="center">{{ item.foodNum }}</uni-td>
            <uni-td align="center">{{ item.foodNum * (item.memberPrice || item.price) }}</uni-td>
            <uni-td align="center">
              <view>
                <u-button type="error" size="small" @click="removeDishes(item)"> 删除</u-button>
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <view class="p-10rpx text-base bg-slate-100">
          <text class="mr-20rpx"
            >已选退菜数量：
            <text class="font-bold">
              {{ retuenDishesList.length }}
            </text>
          </text>
          <text
            >金额：
            <text class="font-bold"> ￥{{ formatMoney(totalMoneyBack) }} </text>
          </text>
        </view>
      </u-col>
    </u-row>

    <!-- <u-row gutter="0"> -->
    <!-- <u-col span="12"> -->
    <view class="rounded-md flex mx-50rpx p-15rpx bg-slate-100 items-center justify-between">
      <view class="flex-col text-base">
        <text class="mr-20rpx block mb-10rpx"
          >退款金额
          <text class="font-bold text-red-500 text-lg"> ￥{{ formatMoney(totalMoneyBack) }} </text>
        </text>
        <text class="block text-slate-500"
          >已扣除优惠补贴, 补贴金额
          <text class="font-bold"> ￥{{ formatMoney(details.mealAllowance) }} </text>
          ，会员折扣：
          <text class="font-bold"> ￥{{ formatMoney(totalDiscount) }} </text>
        </text>
      </view>
      <view class="text-base">
        <u-button
          :disabled="retuenDishesList.length === 0"
          type="error"
          size="large"
          custom-style="padding:10rpx 20rpx;"
          @click="clickConfirm"
          >退款</u-button
        >
      </view>
    </view>
    <!-- </u-col> -->
    <!-- </u-row> -->

    <resultPopup ref="refCommonPopup" @confirm="popupConfirm" :show-icon="false">
      <template #default="{ result }">
        <view v-if="result.mode == 'select-dishes'">
          <view class="bg-slate-100 rounded-md p-10rpx mt-30rpx flex items-center justify-center text-center">
            <text class="block mr-50rpx"> {{ currDishes.foodName }} </text>
            <u-number-box v-model="currDishes.foodNum" :max="getMaxRefundQuantity(currDishes.source)"></u-number-box>
          </view>
          <text class="block text-slate-500 mt-10rpx" v-if="currDishes.refundQuantity > 0">
            当前菜品已退数量 {{ currDishes.refundQuantity }}
          </text>
        </view>
        <view
          v-else-if="result.mode == 'confirm-refund'"
          class="p-10rpx my-30rpx flex-col items-center justify-center text-center"
        >
          <view class="flex-col items-center justify-center text-center">
            <text class="block font-bold text-red-500 text-oxl">￥{{ formatMoney(totalMoneyBack) }} </text>
            <text class="block text-base py-10rpx text-gray-400"> 确认退款金额, 点击退款 </text>
          </view>
        </view>
      </template>
      <template #confirm="{ config }">
        <view class="btns flex">
          <view class="btns-item" @click="refCommonPopup.close()">
            <text class="btns-item-txt"> 取消 </text>
          </view>
          <view class="btns-item confirm" @click="popupConfirm(config)">
            <text class="btns-item-txt"> 确定 </text>
          </view>
        </view>
      </template>
    </resultPopup>

    <!-- 异常提示弹窗 -->
    <resultPopup ref="refResultPopup" :show-icon="true"></resultPopup>
  </view>
</template>
<script lang="ts" setup>
import { onLoad, onPullDownRefresh } from "@dcloudio/uni-app";
import { debounce } from "@kingon/app-tools";
import dayjs from "dayjs";
import { reactive, ref, onMounted, computed } from "vue";
import { getBuffetOrderDetail, onDemandRefund } from "@/api";
import { loadSysDict, getFieldValue, formatMoney } from "@/utils/util";
import resultPopup from "@/components/common-popup/result-popup.vue";

/**
 * source 字段 用于存储原信息，不要修改该引用类型数据，只读
 */

const subsectionList = ["今日", "本周", "本月"];

const curNow = ref(0);

const diningStyles = {
  1: "送餐",
  2: "堂食",
  3: "自提",
};

const payTypes = {
  1: "余额",
  2: "微信",
  3: "支付宝",
  4: "现金",
  5: "套餐",
  6: "刷卡",
  7: "货到付款",
};

// 订单状态（1未出单2已出单、未领 3已领餐、4已送达5逾期6退单7已评论8已派单9待派单10已取消）
const orderStatus = {
  1: "未出单",
  2: "已出单",
  3: "已领餐",
  4: "已送达",
  5: "逾期",
  6: "退单",
  7: "已评论",
  8: "已派单",
  9: "待派单",
  10: "已取消",
};

const getMaxRefundQuantity = (currDishes: any) => {
  if (!currDishes.refundQuantity) return currDishes.foodNum;
  return currDishes.foodNum - currDishes.refundQuantity;
};

const pageStatus = reactive({
  loading: false,
});

// 页面传递的参数
const pagePam = reactive({
  id: "",
});

onLoad((e: any) => {
  pagePam.id = e.id;
  loadSysDict(["sys_payType"]);
});

const orderList = ref([]);

const details = ref({
  payType: "",
});

const getPageData = async () => {
  pageStatus.loading = true;
  try {
    const pam = {
      buffetOrderId: pagePam.id,
    };
    const { data, success } = await getBuffetOrderDetail(pam);
    console.log(data);
    if (!success) throw new Error("获取数据失败");
    details.value = data;
    if (data.buffetOrderItemEntityList) {
      // console.log("----- data.buffetOrderItemEntityList --", data.buffetOrderItemEntityList)
      orderList.value = data.buffetOrderItemEntityList;
    }
    // orderList.value = data.records;
    pageStatus.loading = false;
  } catch (error) {
    pageStatus.loading = false;
    console.error(error);
  }
};

onMounted(async () => {
  getPageData();
});

// 退单按钮点击
const clickReturnDishes = (dishes: any) => {
  const popupConfig = {
    title: "选择退菜数量",
    content: "",
    confirmText: "确认",
    cancelText: "取消",
    autoClose: false,
    //----- 自定义数据
    mode: "select-dishes",
  };
  refCommonPopup.value.open(popupConfig);
  // source 存储一个数据来源引用（不要修改 source）
  currDishes.value = { ...dishes, source: dishes };
};

// 当前选中的菜单项
const currDishes = ref({});

// 弹窗
const refCommonPopup = ref();
const refResultPopup = ref();
const popupConfirmLoadding = ref(false);
// 退款 / 添加退菜确认
const popupConfirm = async (popupConfig: any) => {
  if (popupConfirmLoadding.value === true) return uni.showToast({ title: "正在处理中,请等待", icon: "none" });
  popupConfirmLoadding.value = true;

  if (popupConfig.mode === "select-dishes") {
    // console.log("popupConfirm >> select-dishes");
    // console.log("popupConfirm >> data", currDishes.value);
    refCommonPopup.value.close();
    addDishes(currDishes.value);
  } else if (popupConfig.mode === "confirm-refund") {
    // 调用退款逻辑...

    try {
      const pam = {
        ...details.value,
        //----------------------------------------------------
        // dataType: 3, //工单类型（1服务工单2商品订单3助餐订单4团购订单）
        orderId: details.value.buffetOrderId,
        // orderNum: ordernum,
        // problemDescription: "", // 	问题描述
        refundContent: "消费机操作退菜", // 退款原因
        // refundImg: "", // 退款申请图片凭证
        // refundNum: "", // 售后单号
        // refundType: 1, // 退款类型（1仅退款2退货退款）
        itemList: retuenDishesList.value,
        money: totalMoneyBack.value, // 退款金额
        orderMoney: details.value.money, // 订单金额
      };
      const { data, success } = await onDemandRefund(pam);
      if (success) {
        refResultPopup.value.open({
          title: "成功",
          content: "退款申请提交成功",
          autoClose: true,
          type: "success",
          onClose: () => {
            // 成功则返回并通知
            uni.$emit("refund-success", {
              // result: data
              title: "退款申请提交成功",
              money: details.value.amountcollected,
              order: details.value,
            });

            uni.navigateBack();
          },
        });
      }
    } catch (error) {
      // 失败则停留，并提示原因
      console.error(error);
      refResultPopup.value.open({
        title: "失败",
        content: error.data?.msg || "退款失败，请稍后重试",
        autoClose: true,
        type: "fail",
      });
    }
    refCommonPopup.value.close();
    console.log("popupConfirm >> confirm-refund");
  }

  popupConfirmLoadding.value = false;
};

// 退菜

// 选中的退菜列表
const retuenDishesList = ref([]);
// 退菜列表 （根据选中 过滤）
// const retuenDishesList = computed(() => {
//   return orderList.value.filter((item) => {
//     if (retuenDishes.value.includes(item.buffetOrderItemId)) return item;
//   });
// });

// 是否存在于退菜选中
const haveRetuenDishes = (item: any) => {
  // console.log("haveRetuenDishes >> retuenDishesList", retuenDishesList.value);
  return retuenDishesList.value.some((i) => i.buffetOrderItemId === item.buffetOrderItemId);
};

// 添加退菜
const addDishes = (item: any) => {
  retuenDishesList.value.push({ ...item, orderId: details.value.buffetOrderId });
};

// 删除退菜
const removeDishes = (item: any) => {
  // 查找下标
  const index = retuenDishesList.value.findIndex((i) => i.buffetOrderItemId === item.buffetOrderItemId);
  retuenDishesList.value.splice(index, 1);
};

// 菜单列表总金额
const totalMoney = computed(() => {
  /** @item.memberPrice || item.price memberPrice 为会员价格  */
  return orderList.value.reduce((pre, cur) => {
    return pre + (cur.memberPrice || cur.price) * cur.foodNum;
  }, 0);
  // const money = orderList.value.reduce((pre, cur) => pre + Number(cur.price) * Number(cur.foodNum), 0);
  // return money.toFixed(2);
});

// 退单列表总金额
const totalMoneyBack = computed(() => {
  return retuenDishesList.value.reduce((pre, cur) => {
    return pre + (cur.memberPrice || cur.price) * cur.foodNum;
  }, 0);
  // const money = retuenDishesList.value.reduce((pre, cur) => pre + Number(cur.price) * Number(cur.foodNum), 0);
  // return money.toFixed(2);
});

// 是否确认退款
const clickConfirm = () => {
  const popupConfig = {
    title: "确认退款",
    content: "是否确认退款",
    confirmText: "确认",
    cancelText: "取消",
    autoClose: false,
    //----- 自定义数据
    mode: "confirm-refund",
  };
  refCommonPopup.value.open(popupConfig);
};

// 加算总的会员优惠
const totalDiscount = computed(() => {
  return orderList.value.reduce((pre, cur) => {
    let discount = cur.memberPrice ? (cur.price - cur.memberPrice) * cur.foodNum : 0;
    return pre + discount;
  }, 0);
});
</script>
<style lang="scss" scoped>
.order-details {
  height: 100%;

  ::v-deep .uni-table-scroll {
    height: 160rpx;
    max-height: 160rpx;
    background-color: #f7f7f7;
    border-radius: 5rpx;
    overflow: scroll;
  }

  .food-list {
    width: 100%;
    min-width: none !important;
  }

  ::v-deep .uni-table {
    min-width: auto !important;
  }

  .details-text {
    font-size: 10rpx;
    white-space: nowrap;
    overflow: scroll;

    &.d-name {
      color: rgb(179, 179, 179);
    }

    &.d-price {
      color: red;
      font-weight: bold;
    }

    &.d-price-back {
      color: rgb(14, 187, 52);
      font-weight: bold;
    }
    &.d-price-discount {
      color: orange;
      font-weight: bold;
    }
  }
}

.btns-item {
  background-color: #efefef;
  padding: 5rpx 20rpx;
  border-radius: 5rpx;
  margin: 0rpx 15rpx;
  font-size: 12rpx;
  &.confirm {
    color: white;
    background-color: red;
  }

  .btns-item-txt {
    font-size: 10rpx;
    padding: 5rpx 15rpx;
  }

  ::v-deep .u-button {
    padding: 2rpx 20rpx;
  }
}
</style>
